﻿using Microsoft.AspNetCore.Identity;
using NetCourse.Framework;
using NetCourse.Framework.Security;

namespace XmuAuthen.Services
{
    public class AuthenService : ISingletonDependency
    {
        public CredentialManager credentialManager;

        protected IUserStore userStore;

        public AuthenService(CredentialManager credentialManager, IUserStore userStore)
        {
            this.credentialManager = credentialManager;
            this.userStore = userStore;
        }

        // 登录后，生成并发送 Credential
        public string SignIn(string uN, string pwd)
        {
            IUserPrincipal? user = userStore.GetUser(uN, pwd).user;
            if (user != null)
            {
                string res = credentialManager.GetCredential(user);
                return res;
            }
            else return "";
        }  

        // 检查 Credential 是否有效
        public IUserPrincipal? Check(string credential)
        {
            return credentialManager.GetUser(credential);
        }

        // check, 仅返回user id
        public Guid? GetUserId(string credential)
        {
            var res = credentialManager.GetUser(credential);
            if(res == null) return null;
            else return res.ID;
        }

        // 注销：删除Credential
        public void SignOut(string credential)
        {
            // remove：若credential已被删除，remove返回false，仍能使Cache中无Credential 
            credentialManager.RemoveCredential(credential);
        }

    }
}
